package com.han.spider.safecounty.util;

import java.io.*;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/5/23
 * @Desc:
 */
public class Persistence {

    /**
     * 序列化到本地
     *
     * @param filePath 文件路径
     * @param object   序列化对象
     * @throws IOException io
     */
    public static void serializeToLocal(String filePath, String fileName, Object object) throws IOException {
        File filePaths = new File(filePath);
        if (!filePaths.exists()) {
            filePaths.mkdirs();
        }
        File file = new File(filePath + "/" + fileName);
        try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file))) {

            outputStream.writeObject(object);
        }
    }

    /**
     * 从内存中读取序列化到内存
     *
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @return 序列化对象
     */
    public static Object serializeFromLocal(String filePath, String fileName) {
        File file = new File(filePath + "/" + fileName);
        Object obj = null;
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
            obj = objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return obj;
    }

    /**
     * 写到本地
     *
     * @param data     数据
     * @param filePath 路径
     * @param fileName 名称
     * @throws IOException 异常
     */
    public static void writeToLocal(String data, String filePath, String fileName, boolean isAppend) throws IOException {
        File filePaths = new File(filePath);
        if (!filePaths.exists()) {
            filePaths.mkdirs();
        }
        File file = new File(filePath + "/" + fileName);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, isAppend)))) {
            writer.write(data);
            writer.newLine();
            writer.flush();
        }
    }
}
